package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.DialogInterface
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.NfcA
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.*
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.glory.cqaospda.R
import com.glory.cqaospda.adapter.RejectDataAdapter
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.*
import com.glory.cqaospda.utils.ByteArrayChange
import com.glory.cqaospda.utils.EditTextEnterUtils
import com.glory.cqaospda.viewmodel.SkipDialogModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.glorysoft.hlgdpda.utils.PopWindowsUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.*
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText
import kotlinx.android.synthetic.main.activity_login.*
import java.util.*
import kotlin.collections.ArrayList


class SkipDialogActivity : BaseActivity<SkipDialogModel>() {

    var mNfcAdapter: NfcAdapter? = null
    var mPendingIntent: PendingIntent? = null
    lateinit var mFilters: Array<IntentFilter>
    lateinit var mTechLists: Array<Array<String>>
    private var codePop: PopWindowsUtils.GeneralPop? = null
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@SkipDialogActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }


    private fun initView() {

        FreeApi_ActivityManager.getActivityManager().addActivity(this)
        val extra = intent.getStringExtra("type")

        val instance = MyApp.instance
        instance!!.handler = handler
        FreeApi_LogUtils.saveErrorMessages(extra.toString(), "SkipDialog")
        when {
            extra!!.equals("server_address") -> {
                val addressDialog = getAddressDialog("server_address", object : OnAddressDialog {
                    override fun onAddress(address: String) {
                        val intent = Intent()
                        intent.putExtra("server_address", address)
                        setResult(1, intent)
                    }
                })
                addressDialog.show()
            }
            extra.equals("file_address") -> {
                val addressDialog = getAddressDialog("file_address", object : OnAddressDialog {
                    override fun onAddress(address: String) {
                        val intent = Intent()
                        intent.putExtra("file_address", address)
                        setResult(2, intent)
                    }
                })
                addressDialog.show()
            }
            extra.equals("startjob") -> {
                val addressDialog = getAddressDialog("startjob", object : OnAddressDialog {
                    override fun onAddress(address: String) {
//                        viewModel.defaultLotInfo(address)
                    }
                })
                addressDialog.show()
            }

            extra.equals("materialReplace") -> {
                val type1 = intent.getStringExtra("type1")
                val materialReplaceDialog =
                    getMaterialReplaceDialog(type1.toString(), object : onMaterialListDialog {
                        override fun onMaterialList(materialList: MaterialListBean) {
                            val intent = Intent()
                            intent.putExtra("material", materialList)
                            setResult(1, intent)
                            finish()
                        }
                    })
                materialReplaceDialog.show()
            }

            extra.equals("SelectSite") -> {

                val startjobDialog = getStartjobDialog(object : OnAddressDialog {
                    override fun onAddress(address: String) {
                        val intent = Intent()
                        intent.putExtra("StepName", address)
                        setResult(1, intent)
                    }
                })
                startjobDialog.show()
            }
            extra.equals("StepDesc") -> {
                val startjobDialog = getStepDescDialog("", object : OnAddressDialog {
                    override fun onAddress(address: String) {
                        setResult(2)
                    }
                })
                startjobDialog.show()
            }
            extra.equals("End") -> {

                val addressDialog = getEndPassDialog("End", object : OnEndPassDialog {
                    override fun onEndPass(address: String, mark: String, lead: String) {
                        val intent = Intent()
                        intent.putExtra("pasnum", address)
                        intent.putExtra("mark", mark)
                        intent.putExtra("lead", lead)
                        setResult(3, intent)
                    }
                })
                addressDialog.show()
            }
            extra.equals("Confirm") -> {
                val startjobDialog = getStepDescDialog("Confirm", object : OnAddressDialog {
                    override fun onAddress(address: String) {
                        val intent = Intent()
                        setResult(4, intent)
                    }
                })
                startjobDialog.show()
            }
            extra.equals("inspecDetailsItem") -> {
                val startjobDialog =
                    getStepDescDialog("inspecDetailsItem", object : OnAddressDialog {
                        override fun onAddress(address: String) {
                            val intent = Intent()
                            setResult(1, intent)
                        }
                    })
                startjobDialog.show()
            }
            extra.equals("inspectLot") -> {
                val startjobDialog =
                    getStepDescDialog("inspectLot", object : OnAddressDialog {
                        override fun onAddress(address: String) {
                            val intent = Intent()
                            setResult(2, intent)
                        }
                    })
                startjobDialog.show()
            }
            extra.equals("State") -> {

                val startjobDialog = getStepDescDialog("State", object : OnAddressDialog {
                    override fun onAddress(address: String) {
                        val intent = Intent()
                        setResult(1, intent)
                    }
                })
                startjobDialog.show()
            }
            extra.equals("EndRun") -> {

                val startjobDialog = getStepDescDialog("EndRun", object : OnAddressDialog {
                    override fun onAddress(address: String) {
                        val intent = Intent()
                        intent.putExtra("StepName", address)
                        setResult(5, intent)
                    }
                })
                startjobDialog.show()
            }

            extra.equals("temperature") -> {

                val addressDialog = getAddressDialog("temperature", object : OnAddressDialog {
                    override fun onAddress(address: String) {
                        val intent = Intent()
                        intent.putExtra("temperature", address)
                        setResult(2, intent)
                    }
                })
                addressDialog.show()
            }

            extra.contains("connectTimeout") -> {
                val connectTimeoutDialog =
                    getAddressDialog("connectTimeout", object : OnAddressDialog {
                        override fun onAddress(address: String) {
                            val intent = Intent()
                            intent.putExtra("connectTimeout", address)
                            setResult(4, intent)
                        }
                    })
                connectTimeoutDialog.show()
            }

            extra.contains("EmptyPassingStation") -> {
                val connectTimeoutDialog =
                    getAddressDialog("EmptyPassingStation", object : OnAddressDialog {
                        override fun onAddress(address: String) {
                            val intent = Intent()
                            intent.putExtra("EmptyPassingStation", address)
                            setResult(1, intent)
                        }
                    })
                connectTimeoutDialog.show()
            }

            extra.equals("LotID") -> {
                val types = intent.getStringExtra("types")
                val materialReplaceDialog = getRepairDialog(object : onRepairDialog {
                    override fun onRepair(lot: String, checked: Boolean) {
                        if (types == "mswitch") {
                            viewModel.defaultLotSwitch(lot, checked)
                        } else {
                            viewModel.defaultLotInfo(lot)
                        }
                    }
                })
                materialReplaceDialog.show()
            }
            extra.equals("inspect") -> {
                val addressDialog = getInspectDialog("", object : OnInspectDialog {
                    override fun onInspect(lotId: String, maintenanceItem: String) {
                        val intent = Intent()
                        intent.putExtra("lotId", lotId)
                        intent.putExtra("maintenanceItem", maintenanceItem)
                        setResult(1, intent)
                    }
                })
                addressDialog.show()
            }
            extra.equals("inspect0") -> {
                val addressDialog = getInspectDialog("inspect0", object : OnInspectDialog {
                    override fun onInspect(lotId: String, maintenanceItem: String) {
                        val intent = Intent()
                        intent.putExtra("lotId", lotId)
                        intent.putExtra("maintenanceItem", maintenanceItem)
                        setResult(1, intent)
                    }
                })
                addressDialog.show()
            }
            extra.equals("inspectItem") -> {
                val addressDialog = getInspectItemDialog(object : OnInspectItemDialog {
                    override fun onInspectItem(reason: String) {
                        val intent = Intent()
                        intent.putExtra("reason", reason)
                        setResult(3, intent)
                    }
                })
                addressDialog.show()
            }
            extra.equals("Shiftchange") -> {
                val materialReplaceDialog = getShiftchangeDialog(object : onShiftchangeDialog {
                    override fun onShiftchange(name: String, pass: String) {
                        val intent = Intent()
                        intent.putExtra("name", name)
                        intent.putExtra("pass", pass)
                        setResult(1, intent)
                    }
                })
                materialReplaceDialog.show()
            }

            extra.equals("Error") -> {
                val errorDialog = getErrorStepDescDialog(object : OnAddressDialog {
                    override fun onAddress(address: String) {

                    }
                })
                errorDialog.show()
            }
            extra.equals("BatchTrackOut") -> {
                val errorDialog = getStepDescDialog(object : OnAddressDialog {
                    override fun onAddress(address: String) {

                    }
                })
                errorDialog.show()
            }
            extra.equals("KeyEvent") -> {
                val startjobDialog = getKeyEventDialog("KeyEvent", object : OnAddressDialog {
                    override fun onAddress(address: String) {
                        setResult(108)
                        finish()
                    }
                })
                startjobDialog.show()
            }
            extra.equals("materiaAdapter") -> {
                val showMaterialDialog =
                    showMaterialDialog(object : onMaterialListDialog {
                        override fun onMaterialList(materialList: MaterialListBean) {

                        }
                    })
                showMaterialDialog.show()
            }
            extra.equals("EndRunBean") -> {
                val showMaterialDialog =
                    showEndRunDataDialog(object : onEndRunDataDialog {
                        override fun onEndRunData() {
                            setResult(6)
                            finish()
                        }
                    })
                showMaterialDialog.show()
            }
            extra.equals("RejectData") -> {
                val showRejectDataDialog = showRejectDataDialog()
                showRejectDataDialog.show()
            }
        }

        viewModel.defUI.callObserve.observe(this@SkipDialogActivity) {
            if (!Constant.okgoError) {
                when (it.type) {
                    1 -> {
                        val lotsBean = it.item as LotInfoBean
                        val lotList = ArrayList<LotInfoBean>()
                        lotList.add(lotsBean)
                        val intent = Intent()
                        intent.putExtra("lotBean", lotList)
                        setResult(1, intent)
                        finish()
                    }
                    2 -> {
                        val intent = Intent()
                        setResult(1, intent)
                        finish()
                    }
                    3 -> {
                        val intent = Intent()
                        setResult(2, intent)
                        finish()
                    }
                    4 -> {
                        val accountBean = it.item as AccountBean
                        val intent = Intent()
                        intent.putExtra("name", accountBean.username)
                        intent.putExtra("pass", accountBean.password)
                        setResult(2, intent)
                        finish()
                    }
                }
            } else {
                Constant.okgoError = false
            }
        }

    }


    private fun getAddressDialog(ress: String, address: OnAddressDialog): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_address, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        var lotQty = 0
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_no: TextView = contentView.findViewById(R.id.add_no)
        val title: TextView = contentView.findViewById(R.id.title)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val add_text: TextView = contentView.findViewById(R.id.add_text)
        val etEqpWorkID: EditText = contentView.findViewById(R.id.etEqpWorkID)
        when (ress) {
            "server_address" -> {
                add_text.text = "服务器地址："
                etEqpWorkID.setText(Constant.mUrl)
            }
            "file_address" -> {
                add_text.text = "文件地址："
            }
//            "startjob" -> {
//                title.text = "请扫描LotID"
//                add_text.visibility = View.GONE
//                add_no.visibility = View.GONE
//            }
            "temperature" -> {
                title.text = "封刀温度"
                add_text.text = "温度"
                etEqpWorkID.inputType = InputType.TYPE_CLASS_NUMBER
            }
            "EmptyPassingStation" -> {
                title.text = "请输入分批数量"
                add_text.text = "分批数量"
            }
            "connectTimeout" -> {
                etEqpWorkID.inputType = InputType.TYPE_CLASS_NUMBER
                add_text.text = "网络超时时长："
                val spConnectTimeout = FreeApi_SharePreferencesUtils.getSharePre(
                    "SystemSet",
                    "connectTimeout",
                    applicationContext
                )
                var i: Int
                if (spConnectTimeout.equals("")) {
                    i = Constant.connectTimeout
                } else {
                    i = spConnectTimeout.toInt()
                }
                etEqpWorkID.setText(i.toString())
            }

        }


        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_no.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_yes.setOnClickListener {
            address.onAddress(etEqpWorkID.text.toString())
            dialog.dismiss()
            finish()
        }

        return dialog
    }

    private fun getEndPassDialog(ress: String, address: OnEndPassDialog): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_endpass, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        var lotQty = 0
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_no: TextView = contentView.findViewById(R.id.add_no)
        val title: TextView = contentView.findViewById(R.id.title)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val add_text: TextView = contentView.findViewById(R.id.add_text)
        val etEqpWorkID: EditText = contentView.findViewById(R.id.etEqpWorkID)
        val etMark: EditText = contentView.findViewById(R.id.etMark)
        val etLead: EditText = contentView.findViewById(R.id.etLead)

        etEqpWorkID.inputType = InputType.TYPE_CLASS_NUMBER
        lotQty = intent.getStringExtra("LotQty")!!.toInt()
        val pass = intent.getStringExtra("pass").toString()
        val mark = intent.getStringExtra("mark").toString()
        val lead = intent.getStringExtra("lead").toString()
        etEqpWorkID.setText(pass)
        etMark.setText(mark)
        etLead.setText(lead)

        title.text = ""
        add_no.visibility = View.GONE

        etEqpWorkID.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(
                s: CharSequence,
                start: Int,
                before: Int,
                count: Int
            ) {
            }

            override fun afterTextChanged(s: Editable) {
                if (etEqpWorkID.text.toString().isNotEmpty()) {
                    if (etEqpWorkID.text.toString().toInt() < 0) {
                        etEqpWorkID.setText(0)
                    }
                    if (etEqpWorkID.text.toString().toInt() > lotQty) {
                        etEqpWorkID.setText(lotQty.toString())
                    }
                }
            }
        })


        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_no.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_yes.setOnClickListener {
            address.onEndPass(
                etEqpWorkID.text.toString(),
                etMark.text.toString(),
                etLead.text.toString()
            )
            dialog.dismiss()
            finish()
        }

        return dialog
    }


    private fun getMaterialReplaceDialog(
        type1: String,
        address: onMaterialListDialog
    ): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_material, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_no: TextView = contentView.findViewById(R.id.add_no)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val materialId: EditText = contentView.findViewById(R.id.materialId)
        val materialQty: EditText = contentView.findViewById(R.id.materialQty)
        val materialUnit: EditText = contentView.findViewById(R.id.materialUnit)
        val vendorCode: EditText = contentView.findViewById(R.id.vendorCode)
        val materialCode: EditText = contentView.findViewById(R.id.materialCode)
        val materialUniqueCode: EditText = contentView.findViewById(R.id.materialUniqueCode)
        val list = intent.getSerializableExtra("TypeList") as ArrayList<String>

        dialog.setOnKeyListener(object : DialogInterface.OnKeyListener {
            override fun onKey(p0: DialogInterface?, keyCode: Int, keyEvent: KeyEvent?): Boolean {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    return false
                }
                return false
            }
        })

//        flPositionList.setOnClickListener {
//            if (codePop == null) {
//                codePop = PopWindowsUtils.getOneChoosePop(this, flType.width, list,
//                    ivTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
//                        override fun onSuccess(string: String, potion: Int) {
//                            materialType.text = string
//                        }
//                    }
//                )
//            }
//
//            if (codePop!!.isShowing) {
//                codePop?.dismiss()
//            } else {
//                PopWindowsUtils.setArrowShow(ivTypeArrow)
//                codePop?.showAsDropDown(flType, 0, 0)
//            }
//        }
        val materialList = ArrayList<MaterialListBean>()

        FreeApi_EditTextUtils.setEditTextListener(materialId, this) { s: String? ->
            FreeApi_LogUtils.saveErrorMessages("-$s", "扫描二维码")
            val split = s!!.replace("\n", "")
                .replace("\r","")
                .replace(" ","")
                .split("^")
            if (split.size >= 6) {
                materialId.setText(split[0])
                vendorCode.setText(split[1])
                materialCode.setText(split[2])
                materialUniqueCode.setText(split[3])
                materialQty.setText(split[4])
                materialUnit.setText(split[5])
            }
        }
        FreeApi_EditTextUtils.setEditTextListener(vendorCode, this) { s: String? ->
            FreeApi_LogUtils.saveErrorMessages("-$s", "扫描二维码")
            val split = s!!.replace("\n", "").split("^")
            if (split.size >= 6) {
                materialId.setText(split[0])
                vendorCode.setText(split[1])
                materialCode.setText(split[2])
                materialUniqueCode.setText(split[3])
                materialQty.setText(split[4])
                materialUnit.setText(split[5])
            }
        }
        FreeApi_EditTextUtils.setEditTextListener(materialCode, this) { s: String? ->
            FreeApi_LogUtils.saveErrorMessages("-$s", "扫描二维码")
            val split = s!!.replace("\n", "").split("^")
            if (split.size >= 6) {
                materialId.setText(split[0])
                vendorCode.setText(split[1])
                materialCode.setText(split[2])
                materialUniqueCode.setText(split[3])
                materialQty.setText(split[4])
                materialUnit.setText(split[5])
            }
        }
        FreeApi_EditTextUtils.setEditTextListener(materialUniqueCode, this) { s: String? ->
            FreeApi_LogUtils.saveErrorMessages("-$s", "扫描二维码")
            val split = s!!.replace("\n", "").split("^")
            if (split.size >= 6) {
                materialId.setText(split[0])
                vendorCode.setText(split[1])
                materialCode.setText(split[2])
                materialUniqueCode.setText(split[3])
                materialQty.setText(split[4])
                materialUnit.setText(split[5])
            }
        }
        FreeApi_EditTextUtils.setEditTextListener(materialQty, this) { s: String? ->
            FreeApi_LogUtils.saveErrorMessages("-$s", "扫描二维码")
            val split = s!!.replace("\n", "").split("^")
            if (split.size >= 6) {
                materialId.setText(split[0])
                vendorCode.setText(split[1])
                materialCode.setText(split[2])
                materialUniqueCode.setText(split[3])
                materialQty.setText(split[4])
                materialUnit.setText(split[5])
            }
        }
        FreeApi_EditTextUtils.setEditTextListener(materialUnit, this) { s: String? ->
            FreeApi_LogUtils.saveErrorMessages("-$s", "扫描二维码")
            val split = s!!.replace("\n", "").split("^")
            if (split.size >= 6) {
                materialId.setText(split[0])
                vendorCode.setText(split[1])
                materialCode.setText(split[2])
                materialUniqueCode.setText(split[3])
                materialQty.setText(split[4])
                materialUnit.setText(split[5])
            }
        }


        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_no.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_yes.setOnClickListener {
            if (materialId.text.toString().length < 5) {
                viewModel.defUI.toastEvent.value = ToastMessageBean("请输入正确的料号", true)
                return@setOnClickListener
            }
            val materialListBean = MaterialListBean()
            materialListBean.materialId = materialId.text.toString()
            materialListBean.materialType = ""
//                materialType.text.toString()
            materialListBean.materialQty = materialQty.text.toString()
            materialListBean.materialUnit = materialUnit.text.toString()
            materialListBean.vendorCode = vendorCode.text.toString()
            materialListBean.materialCode = materialCode.text.toString()
            materialListBean.materialUniqueCode = materialUniqueCode.text.toString()
            materialListBean.materialLotId = materialCode.text.toString()
//            materialList.add(materialListBean)

            address.onMaterialList(materialListBean)
            dialog.dismiss()
        }

        return dialog
    }

    private fun showMaterialDialog(
        address: onMaterialListDialog
    ): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_show_rejectdata, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val tvMaterialId: TextView = contentView.findViewById(R.id.tvMaterialId)
        val tvMaterialLOtID: TextView = contentView.findViewById(R.id.tvMaterialLOtID)
        val tvMaterialUniqueCode: TextView = contentView.findViewById(R.id.tvMaterialUniqueCode)
        val tvMaterialQty: TextView = contentView.findViewById(R.id.tvMaterialQty)
        val tvMaterialUnit: TextView = contentView.findViewById(R.id.tvMaterialUnit)
        val tvVendorCode: TextView = contentView.findViewById(R.id.tvVendorCode)
        val data = intent.getSerializableExtra("materiaData") as EqpMaterialsBean.Materialslist
        tvMaterialId.setText(data.mMaterialId)
        tvMaterialLOtID.setText(data.mMateriallotId)
        tvMaterialUniqueCode.setText(data.mMaterialUniqueCode)
        tvMaterialQty.setText(data.mMaterialQty)
        tvMaterialUnit.setText(data.mMaterialUnit)
        tvVendorCode.setText(data.mVendorCode)

        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        return dialog
    }

    private fun showEndRunDataDialog(
        endRun: onEndRunDataDialog
    ): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_show_endrundata, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val tvInputqty: TextView = contentView.findViewById(R.id.tvInputqty)
        val tvOutputqty: TextView = contentView.findViewById(R.id.tvOutputqty)
        val tvYield: TextView = contentView.findViewById(R.id.tvYield)
        val tvBotton: TextView = contentView.findViewById(R.id.tvBotton)
        val tvremark: TextView = contentView.findViewById(R.id.tvremark)
        val title: TextView = contentView.findViewById(R.id.title)
        val tvRemarkTiele: TextView = contentView.findViewById(R.id.tvRemarkTiele)

        val inputqty = intent.getStringExtra("inputqty").toString()
        val outputqty = intent.getStringExtra("outputqty").toString()
        val yieLd = intent.getStringExtra("yield").toString()
        val remark = intent.getStringExtra("remark").toString()

        if (!remark.equals("")){
            title.setTextColor(android.graphics.Color.RED)
            tvRemarkTiele.setTextColor(android.graphics.Color.RED)
            tvremark.setTextColor(android.graphics.Color.RED)
        }

        tvInputqty.text = inputqty
        tvOutputqty.text = outputqty
        tvYield.text = yieLd
        tvremark.text = remark

        tvBotton.setOnClickListener{
            endRun.onEndRunData()
            dialog.dismiss()
        }

        ivClose.setOnClickListener {
            endRun.onEndRunData()
            dialog.dismiss()
        }
        return dialog
    }

    private fun showRejectDataDialog(): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_show_material, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val tvLotId: TextView = contentView.findViewById(R.id.tvLotId)
        val tvDevice: TextView = contentView.findViewById(R.id.tvDevice)
        val tvMesInQty: TextView = contentView.findViewById(R.id.tvMesInQty)
        val tvFailQty: TextView = contentView.findViewById(R.id.tvFailQty)
        val tvOutQty: TextView = contentView.findViewById(R.id.tvOutQty)
        val tvYield: TextView = contentView.findViewById(R.id.tvYield)
        val rvRejectData: RecyclerView = contentView.findViewById(R.id.rvRejectData)
        val data = intent.getSerializableExtra("mesRejectData") as MesRejectBean

        tvLotId.text = data.lotno
        tvDevice.text = data.device
        tvMesInQty.text = data.mes_in_qty
        tvFailQty.text = data.fail_qty
        tvOutQty.text = data.out_qty
        tvYield.text = data.yield

        rvRejectData.layoutManager = LinearLayoutManager(this)
        rvRejectData.itemAnimator = DefaultItemAnimator()
        rvRejectData.addItemDecoration(DividerItemDecoration(this, 1))
        val rejectDataAdapter = RejectDataAdapter(data.rejectinfolist)
        rvRejectData.adapter = rejectDataAdapter

        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        return dialog
    }

    private fun getShiftchangeDialog(address: onShiftchangeDialog): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_shiftchange, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        mPendingIntent = PendingIntent.getActivity(
            this, 0, Intent(
                this,
                javaClass
            ).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0
        )
        // Setup an intent filter for all MIME based dispatches
        val ndef = IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)
        try {
            ndef.addDataType("*/*")
        } catch (e: IntentFilter.MalformedMimeTypeException) {
            throw RuntimeException("fail", e)
        }
        mFilters = arrayOf(ndef)

        // 根据标签类型设置
        mTechLists = arrayOf(arrayOf(NfcA::class.java.name))
        checkNFCFunction()
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_no: TextView = contentView.findViewById(R.id.add_no)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val etName: EditText = contentView.findViewById(R.id.etName)
        val etPass: EditText = contentView.findViewById(R.id.etPass)

        val name = intent.getStringExtra("name")
        val pass = intent.getStringExtra("pass")
        etName.setText(name)
        etPass.setText(pass)
        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_no.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_yes.setOnClickListener {
            if (etName.text.toString().trim { it <= ' ' }.isEmpty()) {
                viewModel.defUI.toastEvent.value = ToastMessageBean("请输入工号", false)
                return@setOnClickListener
            }
            if (etPass.text.toString().trim { it <= ' ' }.isEmpty()) {
                viewModel.defUI.toastEvent.value = ToastMessageBean("请输入密码", false)
                return@setOnClickListener
            }
            address.onShiftchange(etName.text.toString(), etPass.text.toString());
            dialog.dismiss()
            finish()
        }

        return dialog
    }

    private fun getRepairDialog(address: onRepairDialog): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_repair, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()

        val types = intent.getStringExtra("types")

        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_no: TextView = contentView.findViewById(R.id.add_no)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val title: TextView = contentView.findViewById(R.id.title)
        val tvLot: TextView = contentView.findViewById(R.id.tvLot)
        val lotId: EditText = contentView.findViewById(R.id.lotId)
        val reRadioGroup: RelativeLayout = contentView.findViewById(R.id.reRadioGroup)
        val btY: RadioButton = contentView.findViewById(R.id.btY)
        val btN: RadioButton = contentView.findViewById(R.id.btN)

        if ("startjob".equals(types)) {
            title.text = "请扫描LotID"
            tvLot.text = "LotID"
            reRadioGroup.visibility = View.GONE
        }
        if ("mswitch".equals(types)) {
            title.text = "请扫描LotID"
            tvLot.text = "LotID"
            reRadioGroup.visibility = View.VISIBLE
        }

        queryEqpData(lotId, btY.isChecked, address)

        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_no.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_yes.setOnClickListener {
            if (lotId.text.toString() == "") {
                viewModel.defUI.toastEvent.value = ToastMessageBean("批次号不能为空", false)
                return@setOnClickListener
            }
            address.onRepair(lotId.text.toString(), btY.isChecked)
            dialog.dismiss()
        }



        return dialog
    }

    private fun queryEqpData(
        editText: EditText?,
        isChecked: Boolean,
        address: onRepairDialog,
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            address.onRepair(s!!, isChecked)
        }

    }

    private fun getStartjobDialog(address: OnAddressDialog): MaterialDialog {

        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_startjob, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()

        val flType: FrameLayout = contentView.findViewById(R.id.flType)
        val ivTypeArrow: ImageView = contentView.findViewById(R.id.ivTypeArrow)
        val flPositionList: LinearLayout = contentView.findViewById(R.id.flPositionList)
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val region_text: TextView = contentView.findViewById(R.id.tvType)
        val region_yes: TextView = contentView.findViewById(R.id.region_yes)
        val list: ArrayList<String> = ArrayList()
        list.add("FT")
        list.add("RT")
        list.add("EQA")
        list.add("EQART")
        list.add("Detape")
        list.add("OnlineQC")

        flPositionList.setOnClickListener {
            if (codePop == null) {
                codePop = PopWindowsUtils.getOneChoosePop(this, flType.width, list,
                    ivTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                        override fun onSuccess(string: String, potion: Int) {
                            region_text.setText(string)
                        }
                    }
                )
            }

            if (codePop!!.isShowing) {
                codePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivTypeArrow)
                codePop?.showAsDropDown(flType, 0, 0)
            }
        }

        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }

        region_yes.setOnClickListener {
            if (region_text.text.toString() == "") {
                viewModel.defUI.toastEvent.value = ToastMessageBean("请选择站点", false)
                return@setOnClickListener
            }
            address.onAddress(region_text.text.toString())
            dialog.dismiss()
            finish()
        }

        return dialog
    }

    @SuppressLint("SetTextI18n")
    private fun getStepDescDialog(type: String, address: OnAddressDialog): MaterialDialog {

        var Lotid = ""
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_stepdesc, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()

        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val add_no: TextView = contentView.findViewById(R.id.add_no)
        val tvTips: TextView = contentView.findViewById(R.id.tvTips)

        if (type == "Confirm") {
            tvTips.text = "是否结束？"
        }
        if (type == "EndRun") {
            tvTips.text = "是否EndRun？"
        }
        if (type == "inspecDetailsItem") {
            tvTips.text = "盘号不一致，是否继续？"
        }
        if (type == "inspectLot") {
            tvTips.text = "输入的Lot与绑定的Lot不一致，是否继续？"
        }
        if (type == "State") {
            Lotid = intent.getStringExtra("lotID").toString()
            FreeApi_LogUtils.saveErrorMessages(Lotid, "getStepDescDialog")
            if (Lotid == "State") {
                tvTips.text = "该设备正在进行中，是否进入操作页面？"
            } else {
                tvTips.text = "批次" + Lotid + "正在进行中，是否进入操作页面？"
            }
        }
        if (type == "Error") {
            tvTips.text = intent.getStringExtra("error").toString()
            FreeApi_LogUtils.saveErrorMessages(tvTips.text.toString(), "SkipDialog")

            add_yes.visibility = View.GONE
            add_no.text = "确认"
        }

        add_no.setOnClickListener {
            dialog.dismiss()
            finish()
        }

        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }

        add_yes.setOnClickListener {
            address.onAddress(Lotid)
            dialog.dismiss()
            finish()
        }

        return dialog
    }

    @SuppressLint("SetTextI18n")
    private fun getErrorStepDescDialog(address: OnAddressDialog): MaterialDialog {

        var Lotid = ""
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_errorstepdesc, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()

        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val tvTips: TextView = contentView.findViewById(R.id.tvTips)

        tvTips.text = intent.getStringExtra("error").toString()
        FreeApi_LogUtils.saveErrorMessages(tvTips.text.toString(), "SkipDialog")

        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }

        add_yes.setOnClickListener {
            address.onAddress(Lotid)
            dialog.dismiss()
            finish()
        }

        return dialog
    }

    @SuppressLint("SetTextI18n")
    private fun getStepDescDialog(address: OnAddressDialog): MaterialDialog {

        var Lotid = ""
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_endstepdesc, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()

        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val tvLotState: TextView = contentView.findViewById(R.id.tvLotState)
        val tvLotStepName: TextView = contentView.findViewById(R.id.tvLotStepName)

        tvLotState.text = "批次当前的状态："+intent.getStringExtra("LotState").toString()
        tvLotStepName.text = "批次当前的站点："+intent.getStringExtra("LotStepName").toString()

        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }

        add_yes.setOnClickListener {
            address.onAddress(Lotid)
            dialog.dismiss()
            finish()
        }

        return dialog
    }


    private fun getKeyEventDialog(type: String, address: OnAddressDialog): MaterialDialog {

        var Lotid = ""
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_keyevent, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()

        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val add_no: TextView = contentView.findViewById(R.id.add_no)
        val tvTips: TextView = contentView.findViewById(R.id.tvTips)

        add_no.setOnClickListener {
            dialog.dismiss()
            finish()
        }

        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }

        add_yes.setOnClickListener {
            address.onAddress(Lotid)
            dialog.dismiss()
        }

        return dialog
    }


    private fun getInspectDialog(ress: String, inspect: OnInspectDialog): MaterialDialog {

        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_inspect, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_no: TextView = contentView.findViewById(R.id.add_no)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val etLotID: FreeUI_ClearEditText = contentView.findViewById(R.id.etLotID)
        val llReel: LinearLayout = contentView.findViewById(R.id.llReel)
        val maintenanceItem: FreeUI_ClearEditText = contentView.findViewById(R.id.maintenanceItem)

        if (ress == "inspect0"){
            llReel.visibility = View.GONE
        }

        FreeApi_EditTextUtils.setEditTextListener(maintenanceItem, this) { s: String? ->
            val split = s!!.replace("\n", "").split("#")
            FreeApi_LogUtils.saveErrorMessages(split.toString(), "扫描二维码")
            if (split.size >= 2) {
                etLotID.setText(split[0])
                maintenanceItem.setText(split[1])
            }
        }
        FreeApi_EditTextUtils.setEditTextListener(etLotID, this) { s: String? ->
            val split = s!!.replace("\n", "").split("#")
            FreeApi_LogUtils.saveErrorMessages(split.toString(), "扫描二维码")
            if (split.size >= 2) {
                etLotID.setText(split[0])
                maintenanceItem.setText(split[1])
            }
        }

//        queryEqpData(maintenanceItem)
//        queryEqpData(etLotID)



        add_no.setOnClickListener {
            dialog.dismiss()
            finish()
        }

        ivClose.setOnClickListener {

            dialog.dismiss()
            finish()
        }

        add_yes.setOnClickListener {
            if (etLotID.text.toString().trim { it <= ' ' }.isEmpty()) {
                viewModel.defUI.toastEvent.value = ToastMessageBean("请输入LotId", false)
                return@setOnClickListener
            }
            if (ress != "inspect0") {
                if (maintenanceItem.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请输入盘号", false)
                    return@setOnClickListener
                }
            }
            inspect.onInspect(etLotID.text.toString(), maintenanceItem.text.toString())
            dialog.dismiss()
            finish()
        }

        return dialog
    }

    private fun getInspectItemDialog(inspect: OnInspectItemDialog): MaterialDialog {

        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_inspectitem, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_no: TextView = contentView.findViewById(R.id.add_no)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val etReason: FreeUI_ClearEditText = contentView.findViewById(R.id.etReason)

        add_no.setOnClickListener {
            dialog.dismiss()
            finish()
        }

        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }

        add_yes.setOnClickListener {
            inspect.onInspectItem(etReason.text.toString())
            dialog.dismiss()
            finish()
        }

        return dialog
    }

    private fun queryEqpData(
        editText: FreeUI_ClearEditText?,
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            editText!!.setText(s)
        }
    }

    interface OnAddressDialog {
        fun onAddress(address: String)
    }

    interface OnEndPassDialog {
        fun onEndPass(address: String, mark: String, lead: String)
    }

    interface OnInspectDialog {
        fun onInspect(lotId: String, maintenanceItem: String)
    }

    interface OnInspectItemDialog {
        fun onInspectItem(reason: String)
    }

    interface onMaterialListDialog {
        fun onMaterialList(materialList: MaterialListBean)
    }

    interface onEndRunDataDialog {
        fun onEndRunData()
    }

    interface onShiftchangeDialog {
        fun onShiftchange(name: String, pass: String)
    }

    interface onRepairDialog {
        fun onRepair(lot: String, checked: Boolean)
    }

    override fun onPause() {
        super.onPause()
        finish()
    }

    override fun initData() {

    }

    override fun initView(savedInstanceState: Bundle?) {
        initView()
    }

    private fun checkNFCFunction() {
        // TODO Auto-generated method stub
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this)
        // check the NFC adapter first
        if (mNfcAdapter == null) {

            FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "该设备未发现NFC功能", {

            }) {}.show(supportFragmentManager, "SUBMIT_DIALOG")

            return
        } else {
            if (!mNfcAdapter!!.isEnabled) {
                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "NFC未开启,是否去开启？", {
                    val setnfc = Intent(Settings.ACTION_NFC_SETTINGS)
                    startActivity(setnfc)
                }) {}.show(supportFragmentManager, "SUBMIT_DIALOG")
                return
            }
        }
    }

    override fun onResume() {
        super.onResume()
        enableForegroundDispatch()
    }

    private fun enableForegroundDispatch() {
        // TODO 自动生成的方法存根
        if (mNfcAdapter != null) {
            mNfcAdapter!!.enableForegroundDispatch(
                this, mPendingIntent,
                mFilters, mTechLists
            )
        }
    }

    override fun onNewIntent(intent: Intent) {
        // TODO 自动生成的方法存根
        super.onNewIntent(intent)
        val intentActionStr = intent.action // 获取到本次启动的action
        if (NfcAdapter.ACTION_NDEF_DISCOVERED == intentActionStr || NfcAdapter.ACTION_TECH_DISCOVERED == intentActionStr || NfcAdapter.ACTION_TAG_DISCOVERED == intentActionStr) { // 未知类型
            // 在intent中读取Tag id
            val tag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
            val bytesId = tag!!.id // 获取id数组

            viewModel.defaultGetAccount(ByteArrayChange.ByteArrayToHexString(bytesId))
        }
    }


    override fun layoutId(): Int {
        return R.layout.free_ui_layout_tab
    }
}